package com.dts.evaluate.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.support.annotation.Nullable;

import com.dts.evaluate.common.Constants;
import com.dts.evaluate.controller.impl.DataImpl;
import com.dts.evaluate.controller.intf.DataInterface;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.callback.StringCallback;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by user on 2016/9/9.
 */
public class ApkUtil {

    public static void installNewApk(final Context context){
        final String versionName = PackageUtils.getAppVersionName(context);
        DataInterface dataInterface = new DataImpl();
        dataInterface.checkNewVersion(Constants.CHECK_VERSION_URL, Constants.CLIENT_TYPE_VALUE, versionName, new StringCallback() {
            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                if(s != null && s.length() > 0){
                    download(context,s);
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(isFromCache, call, response, e);
                if(isFromCache){
                    LogUtil.v("checker  onError1");
                    checkAgain(context,versionName);
                }
            }
        },context);

    }

    private static void checkAgain(final Context context, String versionName){
        DataInterface dataInterface = new DataImpl();
        dataInterface.checkNewVersion(Constants.CHECK_VERSION_URL, Constants.CLIENT_TYPE_VALUE, versionName, new StringCallback() {
            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                LogUtil.v("dowload:"+s);
                if(!StringUtils.isEmpty(s)){
                    download(context,s);
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(isFromCache, call, response, e);
                if(isFromCache){
                    LogUtil.v("checker  onError2");
                }
            }
        },context);
    }

    /**
     * 下载应用程序
     * @param url
     */
    private static void download(final Context context, String url){
        final ProgressDialog dialog = new ProgressDialog(context);
        dialog.setIndeterminate(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL );
        dialog.setTitle("发现新版本，正在下载");
        DataInterface dataInterface = new DataImpl();
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String name = "new.apk";
        dataInterface.downloadNewVersion(url, new FileCallback(dir.getAbsolutePath(),name) {
            @Override
            public void onResponse(boolean isFromCache, File file, Request request, @Nullable Response response) {

                if(file != null && file.exists()){
                    LogUtil.v("下载完成");
                    dialog.dismiss();
                   /* SharedPreferences sharedPreferences = getSharedPreferences(Constants.HAS_NEW_APK,MODE_PRIVATE);
                    sharedPreferences.edit().putBoolean(Constants.HAS_NEW_APK,true).commit();*/
                    PackageUtils.installNormal(context,file.getAbsolutePath());
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(isFromCache, call, response, e);
            }

            @Override
            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                LogUtil.v("downloadProgress "+"currentSize:"+currentSize+"  totalSize:"+totalSize);
                if(dialog.getProgress() == 0){
                    dialog.show();
                    dialog.setMax((int) totalSize);
                }
                dialog.setProgress((int) currentSize);

            }
        }, context);
    }

}
